<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/13
 * Time: 22:07
 */
namespace app\model;


use think\facade\Db;
use think\Model;

class Cleaning extends Model
{

    private function _getOutField(){
        return [
            'cleaning_id' => 'cleaningId',
            'cleaning_name' => 'pername',
            'cleaning_time' => 'cleaningTime',
            'cp_id' => 'cleaningPointId',
            'cp_name' => 'cleaningPointName',
        ];
    }
    public function addOneCleaning($data){
        $data['cleaning_create_time'] = time();
        return Db::table('cleaning')->insertGetId($data);
    }

    public function getTodayTotalCountByUidAndPointId($uid,$pointId){
        $where = [
            ['cleaning_uid','=',$uid],
            ['cleaning_point_id','=',$pointId],
            ['cleaning_status','=',1],
            ['cleaning_time','>=',date('Y-m-d')],
            ['cleaning_time','<=',time()],
        ];
        return Db::table('cleaning')->where($where)->count();
    }

    public function getCleaningAllCountByWhere($where)
    {
        return Db::table('cleaning')->where($where)->count();
    }

    public function getCleaningListByWhere($where,$field = '',$group = 'cleaning_id')
    {
        $field = $field ? $field : self::_getOutField();
        return Db::table('cleaning')
            ->leftJoin('cleaning_point','cp_id=cleaning_point_id')
            ->where($where)
            ->field($field)
            ->group($group)
            ->select();
    }
    public function getTodayLastInfoByPointId($pointId,$fields = ""){

        $fields = $fields ? $fields : self::_getOutField();
        $where = [
            ['cleaning_point_id','=',$pointId],
            ['cleaning_status','=',1],
            ['cleaning_time','>=',date('Y-m-d')],
            ['cleaning_time','<=',time()],
        ];
        return Db::table('cleaning')
            ->leftJoin('cleaning_point','cp_id=cleaning_point_id')
            ->field($fields)
            ->where($where)
            ->order('cleaning_id desc')
            ->limit(1)
            ->find();
    }

    public function getCleaningMonthListByWhere($where,$monthWhere)
    {
        $sql = "SELECT
	datelist as dday,
	IFNULL(t1.cnt,0) as cnt
FROM
	calendar
	LEFT JOIN (
	SELECT 
		FROM_UNIXTIME( cleaning_time, '%Y-%m-%d' ) AS dday,
		count( cleaning_id ) AS cnt 
	FROM
		`cleaning` 
	WHERE
		{$where}
	GROUP BY
	dday 
	) t1 on calendar.datelist=t1.dday
	where {$monthWhere} GROUP BY datelist";

        return Db::query($sql);

    }
}